package com.dogegg.lbblog.intercept;

import org.springframework.core.MethodClassKey;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class AnnotationLogRecordOperationSource implements LogRecordOperationSource {

    private final LogRecordOperation NULL_INSTANCE = new LogRecordOperation();
    private LogAnnotationParser logAnnotationParser = new SpringLogAnnotationParser();
    private Map<Object, LogRecordOperation> cacheOperations  = new ConcurrentHashMap<>();

    @Override
    public LogRecordOperation getCachedOperation(Method method, Class<?> targetClass,boolean enableCache) {
        if(enableCache){
            Object key  = getCacheKey(method,targetClass);
            LogRecordOperation logRecordOperation = cacheOperations.get(key);
            if(logRecordOperation != null){
                return  logRecordOperation == NULL_INSTANCE ? null:logRecordOperation;
            }
            logRecordOperation = logAnnotationParser.parseLogAnnotation(method);
            cacheOperations.put(key,logRecordOperation == null ? NULL_INSTANCE:logRecordOperation);
            return logRecordOperation;
        }else {
            return logAnnotationParser.parseLogAnnotation(method);
        }

    }

    protected Object getCacheKey(Method method, Class<?> targetClass) {
        return new MethodClassKey(method, targetClass);
    }

}
